package bairui.international.console.web.controller.prize.nine;

import javax.validation.Valid;

import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.PathVariable;
import org.springframework.web.bind.annotation.PostMapping;
import org.springframework.web.bind.annotation.ResponseBody;
import org.springframework.web.multipart.MultipartFile;

import com.lianjing.sh.project.commons.util.Util_FileDeal;
import com.lianjing.sh.spring.web.controller.base.action.Action;
import com.lianjing.sh.spring.web.controller.enhance.output.FomatOutput;
import com.lianjing.sh.validate.spring.exception.ValidateObjectException;
import com.sh_lianjing.util.Util_BeanCopyByDeclaredProperties;

import bairui.international.model.domain.jpa.TB_Prize;
import bairui.international.model.domain.jpa.TB_PrizeItem;
import bairui.international.service.Service_PrizeItem;

/**
 *
 * 奖品管理
 *
 * @generated
 * 
 * @see STest_C_Prize_Nine_ItemManage_FileUpload 测试
 *
 */
@Controller
public class C_Prize_Nine_ItemManage_FileUpload
 extends SC_Prize_Nine_ItemManage_FileUpload 
{
	
	@Autowired private Service_PrizeItem service_PrizeItem;
	
	/**
	 * 上传文件
	 */
	@Action(FileUpload.class)
	@PostMapping(FileUpload.RequestMappingValue)
	public @FomatOutput @ResponseBody Object fileUpload(
		@Valid Input_FileUpload_Input_Upload.Model input, 
		@PathVariable(name=FileUpload.PathVariableName.PrizeId) long prizeId
	) throws Exception {
		long count = service_PrizeItem.count(it->it.prize.id.eq(prizeId));
		// 验证
		MultipartFile[] files = input.getFileUrlFile();
		long maxCount = 8 - count;
		if(maxCount - files.length < 0){
			throw new ValidateObjectException("object", "", "最多还能上传" + maxCount + "张图片");
		}
		//
		for(MultipartFile item : files){
			TB_PrizeItem bean = new TB_PrizeItem();
			// 上传文件相关
			Util_FileDeal
				.saveFile(item, pathConfig.getPosition_Image_PrizeItem())
				.resultTo(bean);
			// 保存数据
			TB_PrizeItem save = Util_BeanCopyByDeclaredProperties.copyProperties(input, bean);
				save.setPrize(new TB_Prize(prizeId));
				save.setNoPrizeFlag(false);
			service_PrizeItem.save(save);
		}
		return null;
	}
	

}
